<template>
  <div class="intention-label-container">
    <!-- 默认规则设置 -->
    <div class="default-rule-card">
      <div class="card-header">
        <div class="card-title">
          <Icon icon="ep:setting" class="title-icon" />
          <span>默认规则设置</span>
        </div>
      </div>
      <div class="card-content">
        <div class="rule-setting">
          <div class="setting-label">
            <Icon icon="ep:info-filled" class="label-icon" />
            <span>当以下所有规则均不满足时，将客户设置为</span>
          </div>
          <el-select
            v-model="classModel"
            placeholder="请选择默认标签"
            class="default-select"
            @change="setClassModel"
          >
            <el-option
              v-for="dict in levelOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            >
              <div class="option-content">
                <el-tag
                  :style="{
                    background: dict.bgColor,
                    color: dict.textColor,
                    border: 'none'
                  }"
                  class="option-tag"
                >
                  {{ dict.name }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
        </div>
        <div class="action-buttons">
          <el-button type="primary" @click="addFrom('add', null)" class="add-btn">
            <Icon icon="ep:plus" class="btn-icon" />
            添加规则
          </el-button>
          <el-button type="success" @click="setSystemDefault" class="default-btn">
            <Icon icon="ep:refresh" class="btn-icon" />
            恢复系统默认规则
          </el-button>
        </div>
      </div>
    </div>

    <!-- 规则列表 -->
    <div class="rules-card">
      <div class="card-header">
        <div class="card-title">
          <Icon icon="ep:list" class="title-icon" />
          <span>意向识别规则</span>
          <div class="rule-stats">
            <span class="stats-text">共 {{ total }} 条规则</span>
          </div>
        </div>
      </div>
      <div class="card-content">
        <div class="table-container">
          <el-table :data="list" class="rules-table" height="300px">
            <el-table-column label="规则条件" min-width="300">
              <template #default="scope">
                <div class="rule-conditions">
                  <Icon icon="ep:operation" class="condition-icon" />
                  <span class="condition-text">
                    {{
                      scope.row.ivrIntentionlabelQueryDOList
                        ? echoDetail(scope.row.ivrIntentionlabelQueryDOList)
                        : '暂无条件'
                    }}
                  </span>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="levelName" label="客户意向标签" align="center" width="180">
              <template #default="scope">
                <div class="label-cell">
                  <el-tag
                    :style="{
                      background: scope.row.bgColor,
                      color: scope.row.textColor,
                      border: 'none'
                    }"
                    class="intention-tag"
                  >
                    <Icon icon="ep:price-tag" class="tag-icon" />
                    {{ scope.row.levelName }}
                  </el-tag>
                </div>
              </template>
            </el-table-column>

            <el-table-column prop="matchingNum" label="匹配次数" align="center" width="120">
              <template #default="scope">
                <div class="match-count">
                  <Icon icon="ep:data-analysis" class="count-icon" />
                  <span class="count-number">{{ scope.row.matchingNum || 0 }}</span>
                </div>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="200" fixed="right">
              <template #default="scope">
                <div class="action-buttons">
                  <el-button
                    type="primary"
                    text
                    @click="addFrom('update', scope.row.id)"
                    class="action-btn"
                  >
                    <Icon icon="ep:edit" class="btn-icon" />
                    编辑
                  </el-button>
                  <el-button type="danger" text @click="removeFrom(scope.row)" class="action-btn">
                    <Icon icon="ep:delete" class="btn-icon" />
                    移除
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>

          <div class="pagination-wrapper">
            <Pagination
              :total="total"
              v-model:page="queryParams.pageNo"
              v-model:limit="queryParams.pageSize"
              @pagination="getList"
            />
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 弹窗组件 -->
  <DialogFrom ref="dialogRef" @success="getList" />
  <DefaltRule ref="defaultRef" @success="getList" />
</template>

<script setup>
import {
  getByFlowId,
  updateGetByFlowId,
  getIntentionLabel,
  deleteIntentionLabel
} from '@/api/call/ivr/index'
import * as LevelApi from '@/api/crm/customerTagConfig'
import DialogFrom from './components/dialog.vue'
import DefaltRule from './components/defaltRule.vue'

defineOptions({ name: 'IntentionLabel' })

const message = useMessage()
const dialogRef = ref(null)
const defaultRef = ref(null)

const props = defineProps({
  ivrId: String,
  groupId: String
})

const list = ref([])
const total = ref(0)
const classModel = ref(null)
const classModelId = ref(null)
const levelOptions = ref([])

const queryParams = reactive({
  flowId: '',
  pageNo: 1,
  pageSize: 10
})

// 匹配类型
const matchType = {
  1: '命中所有问题',
  2: '命中业务问题',
  3: '肯定次数',
  4: '拒绝次数',
  5: '客户讲话次数',
  6: '通话时长',
  7: '客户通话内容',
  8: '走完主流程',
  9: '客户说最后一句'
}

// 匹配符号
const matchSymbols = {
  1: '等于',
  2: '大于等于',
  3: '小于等于'
}

const mathcOptions = {
  1: '包含1个以上',
  2: '包含2个以上',
  3: '包含3个以上',
  4: '包含4个以上',
  5: '包含5个以上',
  6: '包含6个以上',
  7: '包含7个以上',
  8: '包含8个以上',
  9: '包含9个以上',
  10: '包含10个以上',
  0: '包含全部'
}

const endOption = {
  1: '肯定',
  2: '否定',
  3: '拒绝',
  4: '未识别'
}

// 获取将客户设置为
const getByFlowIdDetail = async () => {
  try {
    const { labelType, id } = await getByFlowId({ flowId: queryParams.flowId })
    classModel.value = labelType
    classModelId.value = id
  } catch (error) {
    console.error('获取默认标签失败:', error)
  }
}

// 更新将客户设置为
const setClassModel = async () => {
  try {
    await updateGetByFlowId({
      id: classModelId.value,
      flowId: props.ivrId,
      labelType: classModel.value
    })
    ElMessage.success('操作成功')
  } catch (error) {
    console.error('更新默认标签失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

// 列表
const getList = async () => {
  try {
    const data = await getIntentionLabel(queryParams)
    list.value = data.list
    total.value = data.total
  } catch (error) {
    console.error('获取规则列表失败:', error)
  }
}

// 设置默认
const setSystemDefault = () => {
  defaultRef.value.open(queryParams.flowId)
}

// 新增 编辑
const addFrom = (type, id) => {
  dialogRef.value.open(type, id, queryParams.flowId, levelOptions.value)
}

// 移除
const removeFrom = async (row) => {
  try {
    await message.delConfirm()
    await deleteIntentionLabel(row.id)
    ElMessage.success('操作成功')
    queryParams.pageNo = 1
    getList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除规则失败:', error)
      ElMessage.error('删除失败，请重试')
    }
  }
}

// 回显详情
const echoDetail = (value) => {
  const data = value.map((item) => {
    return (
      '【' +
      matchType[item.selectType] +
      ' ' +
      (item.selectType != 7 && item.selectType != 8 ? matchSymbols[item.query] : '') +
      ' ' +
      (item.selectType == 7 || item.selectType == 8
        ? item.selectType == 7
          ? mathcOptions[item.value]
          : ''
        : item.value) +
      (item.selectType == 7 ? item.keys : '') +
      (item.selectType == 9 ? endOption[item.value] : '') +
      '】'
    )
  })
  return data.join('并且')
}

// 监听props变化
watch(
  () => props.ivrId,
  (val) => {
    if (val) {
      queryParams.flowId = val
      getList()
      getByFlowIdDetail()
    }
  },
  { deep: true }
)

// 初始化
onMounted(async () => {
  try {
    levelOptions.value = await LevelApi.getLevelSimple()
  } catch (error) {
    console.error('获取标签选项失败:', error)
  }
})
</script>

<style lang="scss" scoped>
.intention-label-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  height: calc(100% - 64px);
  gap: 24px;
}

/* 页面头部 */
.page-header {
  background: linear-gradient(135deg, #97a5e2 0%, #7db5db 100%);
  border-radius: 16px;
  padding: 12px 24px;
  color: white;
  position: relative;
  overflow: hidden;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    width: 150px;
    height: 150px;
    background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 0%, transparent 70%);
    border-radius: 50%;
  }
}

.header-content {
  position: relative;
  z-index: 1;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  backdrop-filter: blur(10px);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  margin: 0 0 4px 0;
}

.page-subtitle {
  font-size: 14px;
  margin: 0;
  opacity: 0.9;
}

.rules-card {
  height: calc(100vh - 388px);
}
/* 卡片样式 */
.default-rule-card,
.rules-card {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  backdrop-filter: blur(10px);
  overflow: hidden;
  transition: all 0.2s ease;
  &:hover {
    box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  }
}

.card-header {
  padding: 20px 24px 16px;
  border-bottom: 1px solid rgba(0, 82, 204, 0.1);
  background: linear-gradient(135deg, rgba(0, 82, 204, 0.02) 0%, transparent 100%);
}

.card-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.title-icon {
  color: #0052cc;
  font-size: 18px;
}

.rule-stats {
  margin-left: auto;
  padding: 4px 12px;
  background: rgba(0, 82, 204, 0.1);
  border-radius: 12px;
}

.stats-text {
  font-size: 12px;
  color: #0052cc;
  font-weight: 500;
}

.card-content {
  padding: 24px;
}

/* 默认规则设置 */
.rule-setting {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, rgba(0, 82, 204, 0.05) 0%, rgba(0, 82, 204, 0.02) 100%);
  border-radius: 12px;
  border: 1px solid rgba(0, 82, 204, 0.1);
}

.setting-label {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  font-weight: 500;
  color: #374151;
  white-space: nowrap;
}

.label-icon {
  color: #0052cc;
  font-size: 16px;
}

.default-select {
  min-width: 200px;

  :deep(.el-input__wrapper) {
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: all 0.2s ease;

    &:hover {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.1);
    }

    &.is-focus {
      box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
    }
  }
}

.option-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.option-tag {
  border-radius: 12px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-left: auto;
}

.add-btn {
  background: linear-gradient(135deg, #0052cc 0%, #1d4ed8 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

.default-btn {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  border: none;
  border-radius: 8px;

  .btn-icon {
    margin-right: 6px;
  }
}

/* 表格样式 */
.table-container {
  border-radius: 12px;
  overflow: hidden;
}

.rules-table {
  :deep(.el-table__header) {
    background: rgba(0, 82, 204, 0.02);
  }

  :deep(.el-table__header th) {
    background: transparent;
    border-bottom: 1px solid rgba(0, 82, 204, 0.1);
    color: #374151;
    font-weight: 600;
  }

  :deep(.el-table__body tr:hover) {
    background: rgba(0, 82, 204, 0.02);
  }

  :deep(.el-table__body td) {
    border-bottom: 1px solid rgba(0, 82, 204, 0.05);
  }
}

.rule-conditions {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  padding: 8px 0;
}

.condition-icon {
  color: #6b7280;
  font-size: 16px;
  margin-top: 2px;
  flex-shrink: 0;
}

.condition-text {
  font-size: 13px;
  line-height: 1.5;
  color: #374151;
  word-break: break-all;
}

.label-cell {
  display: flex;
  justify-content: center;
}

.intention-tag {
  display: flex;
  align-items: center;
  gap: 4px;
  border-radius: 12px;
  font-weight: 500;
  padding: 6px 12px;
}

.tag-icon {
  font-size: 12px;
}

.match-count {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
}

.count-icon {
  color: #6b7280;
  font-size: 14px;
}

.count-number {
  font-weight: 600;
  color: #374151;
}

.action-btn {
  padding: 6px 12px;
  border-radius: 6px;
  font-size: 13px;

  .btn-icon {
    margin-right: 4px;
    font-size: 12px;
  }
}

.pagination-wrapper {
  padding: 16px 0;
  display: flex;
  justify-content: center;
}

/* 响应式设计 - H5兼容 */
@media (max-width: 768px) {
  .intention-label-container {
    padding: 12px;
    gap: 16px;
  }

  .page-header {
    padding: 20px;
  }

  .header-left {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }

  .card-header {
    padding: 16px 20px 12px;
  }

  .card-content {
    padding: 20px;
  }

  .rule-setting {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .setting-label {
    justify-content: center;
    white-space: normal;
    text-align: center;
  }

  .action-buttons {
    flex-direction: column;
    margin-left: 0;
    gap: 8px;
  }

  .add-btn,
  .default-btn {
    width: 100%;
  }

  .rules-table {
    :deep(.el-table__body) {
      font-size: 13px;
    }
  }

  .condition-text {
    font-size: 12px;
  }
}

@media (max-width: 480px) {
  .intention-label-container {
    padding: 8px;
  }

  .page-header {
    padding: 16px;
  }

  .page-title {
    font-size: 20px;
  }

  .card-header {
    padding: 12px 16px 8px;
  }

  .card-content {
    padding: 16px;
  }

  .rule-setting {
    padding: 16px;
  }
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .intention-label-container {
    background: linear-gradient(135deg, #1f2937 0%, #111827 100%);
  }

  .default-rule-card,
  .rules-card {
    background: rgba(30, 41, 59, 0.95);
  }

  .page-title {
    color: #f9fafb;
  }

  .card-title {
    color: #f9fafb;
  }

  .setting-label {
    color: #e5e7eb;
  }

  .condition-text {
    color: #d1d5db;
  }

  .count-number {
    color: #e5e7eb;
  }
}
</style>
